package com.esiran.payadmin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.esiran.payadmin.dao.MenuDao;
import com.esiran.payadmin.dao.UserDao;
import com.esiran.payadmin.exception.APIRespException;
import com.esiran.payadmin.model.Menu;
import com.esiran.payadmin.model.User;
import com.esiran.payadmin.service.MenuService;
import com.esiran.payadmin.service.UserService;
import com.esiran.payadmin.util.EncryptUtil;
import com.esiran.payadmin.util.JWTUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Override
    public String login(String username, String password) throws APIRespException {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.where("name = {0}",username);
        User user = this.selectOne(wrapper);
        if (user == null){
            throw new APIRespException("用户不存在",-1);
        }
        String realPassword = user.getPassword().toUpperCase();
        String inputPassword = password.toUpperCase();
        if (!realPassword.equals(inputPassword)){
            throw new APIRespException("密码错误",-1);
        }
        return createUserToken(user.getId().toString());
    }

    private String createUserToken(String username){
        return JWTUtil.createAccessToken()
                .withSubject(username)
                .sign(JWTUtil.getAlgorithm());
    }
}
